package alarm_monitor

import (
	"context"
	"device-admin/config/redis"
	"device-admin/internal/dal"
	"device-admin/internal/dao"
	"device-admin/internal/define"
	"time"
)

type AlarmFilter struct {
	robotID   string
	alarmType int
	dstStatus int
	handlers  []func(robotID string, alarmType int, dstStatus int) bool
}

func NewFilter(robotID string, alarmType int, dstStatus int) *AlarmFilter {
	af := &AlarmFilter{}
	af.robotID = robotID
	af.alarmType = alarmType
	af.dstStatus = dstStatus
	af.handlers = append(af.handlers, af.filterOffline) // 过滤离线告警
	af.handlers = append(af.handlers, af.filterUnused)  // 过滤不再使用的设备
	return af
}

// Filter 告警过滤
func (af *AlarmFilter) Filter() bool {
	for _, handler := range af.handlers {
		if handler(af.robotID, af.alarmType, af.dstStatus) {
			return true
		}
	}
	return false
}

// FilterOffline 过滤离线告警
func (af *AlarmFilter) filterOffline(robotID string, alarmType int, dstStatus int) bool {
	if (alarmType == 2003 || alarmType == 2006 || alarmType == 2009) && (dstStatus == 1 || dstStatus == 2) {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()
		chargingStatus, _ := redis.NewDB().HGet(ctx, define.RedisRobotRTMap+robotID, "charging_status").Result()
		if chargingStatus == "1" {
			return true
		}
	}
	return false
}

// FilterUnused 过滤的不用的设备
func (af *AlarmFilter) filterUnused(robotID string, alarmType int, dstStatus int) bool {
	detail, err := dao.Device{}.Detail(context.Background(), dal.Q, robotID)
	if err == nil && detail != nil {
		if detail.MerchantID == "1" {
			return true
		}
	}
	return false
}
